package stark.app.function.print;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.text.TextUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hjq.bar.TitleBar;

import androidx.annotation.NonNull;
import stark.app.R;
import stark.app.databinding.ActivityPrintWebBinding;
import stark.common.basic.base.BaseTitleBarActivity;
import stark.common.basic.constant.Extra;
import stark.common.basic.utils.IntentUtil;

/**
 * Author：daizhongbin on 2022/7/23
 * Email：1027154338@qq.com
 * Desc:
 */
public class PrintWebActivity extends BaseTitleBarActivity<ActivityPrintWebBinding> {

    public static void start(Context context, String url) {
        Intent intent = IntentUtil.getIntent(context, PrintWebActivity.class);
        intent.putExtra(Extra.PATH, url);
        context.startActivity(intent);
    }

    @NonNull
    @Override
    protected TitleBar getTitleBar() {
        return mDataBinding.titleBar;
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_print_web;
    }

    @Override
    protected void initData() {
        String url = null;
        Intent intent = getIntent();
        url = intent.getStringExtra(Extra.PATH);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        mDataBinding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                } else {
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
        mDataBinding.webView.getSettings().setJavaScriptEnabled(true);
        mDataBinding.webView.loadUrl(url);

        mDataBinding.btnPrint.setOnClickListener(v -> {
            clickPrint();
        });
    }

    private void clickPrint() {
        PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
        PrintDocumentAdapter adapter = mDataBinding.webView.createPrintDocumentAdapter("web");
        printManager.print("web", adapter, null);
    }
}
